<template>

  <div class="user">
    <!--搜索表单-->
    <div class="common-seach-wrap">
      <el-form size="small" :label-width="50" :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="职业">
          <el-select size="small" v-model="searchForm.career_id" placeholder="请选择">
            <el-option label="全部" :value="0"></el-option>
            <el-option v-for="(item, index) in positionList" :key="index" :label="item.title"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="级别">
          <el-select size="small" v-model="searchForm.level_id" placeholder="请选择">
            <el-option label="全部" :value="0"></el-option>
            <el-option v-for="(item, index) in levelList" :key="index" :label="item.title"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方向">
          <el-select size="small" v-model="searchForm.direction_id" placeholder="请选择">
            <el-option label="全部" :value="0"></el-option>
            <el-option v-for="(item, index) in directionList" :key="index" :label="item.title"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input size="small" v-model="searchForm.mobile" maxlength="11" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="姓名 ">
          <el-input size="small" v-model="searchForm.userName" maxlength="10" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="鉴定站">
          <el-select size="small" v-model="searchForm.appraisal_id" placeholder="请选择">
            <el-option label="全部" :value="0"></el-option>
            <el-option v-for="(item, index) in appraisalList" :key="index" :label="item.appraisal"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="common-content">
      <!--添加管理员-->
      <div class="d-b-s">
        <div class="common-level-rail">
          <el-button size="small" type="primary" @click="addClick()">新增学员</el-button>
          <el-button size="small" type="primary" @click="openImport">导入学员</el-button>
          <el-button size="small" type="text" @click="downloadStudentTemplate">下载导入模板</el-button>
        </div>
        <div class="common-level-rail">
          <el-button size="small" type="primary"
            @click="$router.push('/studentManagement/list/statistics')">学习统计</el-button>
        </div>
      </div>

      <!--内容-->
      <div class="product-content">
        <div class="table-wrap">
          <el-table size="small" :data="tableData" style="width: 100%" v-loading="loading">
            <el-table-column align="center" min-width="100" prop="mobile" label="手机号"></el-table-column>
            <el-table-column align="center" min-width="100" prop="userName" label="姓名"></el-table-column>
            <el-table-column align="center" min-width="120" prop="career_title" label="职业"></el-table-column>
            <el-table-column align="center" min-width="120" prop="level_title" label="级别"></el-table-column>
            <el-table-column align="center" min-width="120" prop="direction_title" label="方向"></el-table-column>
            <el-table-column align="center" min-width="120" prop="appraisal_title" label="鉴定站"></el-table-column>
            <el-table-column align="center" min-width="100" prop="status" label="账号状态">
              <template #default="scope">
                <div class="d-c-c">
                  <div class="active-status" :style="scope.row.is_delete === 1 ? 'background: rgba(0,0,0,0.25)' : ''">
                  </div>
                  <div>{{ scope.row.is_delete === 1 ? '关闭' : '开启' }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" min-width="140" prop="create_time" label="创建时间"></el-table-column>
            <el-table-column align="center" min-width="180" prop="notes" label="备注"></el-table-column>
            <el-table-column align="center" fixed="right" label="操作" width="90">
              <template #default="scope">
                <el-button @click="editClick(scope.row)" type="text" size="small">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!--分页-->
        <div class="pagination">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" background
            :current-page="curPage" :page-size="pageSize" layout="total, prev, pager, next, jumper"
            :total="totalDataNumber"></el-pagination>
        </div>
      </div>
    </div>


    <Add v-if="open_add" ref="studentAdd" :title="title" @close="closeAdd"></Add>
    <ImportStudent v-if="open_edit" @close="closeEdit"></ImportStudent>
    <el-dialog class="importList" v-model="visible" :show-close="false" width="1000">
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header d-b-c">
          <el-button size="small" type="primary" @click="downLoadExcel">导出</el-button>
          <el-button type="text">
            <el-icon @click="visible = false">
              <Close style="color: #333" />
            </el-icon>
          </el-button>
        </div>
      </template>
      <div style="padding-bottom: 10px;">成功{{ successInfo.successCount || 0 }}条，失败{{ successInfo.failureCount || 0 }}条
      </div>
      <el-table size="small" :data="failureReasons" style="width: 100%" height="400">
        <el-table-column align="center" min-width="100" prop="mobile" label="手机号"></el-table-column>
        <el-table-column align="center" min-width="100" prop="userName" label="姓名"></el-table-column>
        <el-table-column align="center" min-width="120" prop="career_title" label="职业"></el-table-column>
        <el-table-column align="center" min-width="120" prop="level_title" label="级别"></el-table-column>
        <el-table-column align="center" min-width="120" prop="direction_title" label="方向"></el-table-column>
        <el-table-column align="center" min-width="120" prop="appraisal_title" label="鉴定站"></el-table-column>
        <el-table-column align="center" min-width="100" prop="is_delete" label="状态">
          <template #default="scope">
            <div class="d-c-c">
              <div class="active-status" :style="scope.row.is_delete === 1 ? 'background: rgba(0,0,0,0.25)' : ''">
              </div>
              <div>{{ scope.row.is_delete === 1 ? '关闭' : '开启' }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" min-width="180" prop="notes" label="备注"></el-table-column>
        <el-table-column align="center" min-width="100" prop="status" label="导入结果">
          <template #default="scope">
            <div class="d-c-c">
              <div class="active-status" :style="scope.row.result === '失败' ? 'background: rgba(0,0,0,0.25)' : ''">
              </div>
              <div>{{ scope.row.result === '失败' ? '失败' : '成功' }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" min-width="180" prop="msg" label="失败原因"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import AuthApi from '@/api/auth.js';
import PositionApi from '@/api/position.js';
import StudentApi from '@/api/student.js';
import Add from './dialog/Add.vue';
import ImportStudent from './dialog/ImportStudent.vue';
import { saveAs } from 'file-saver';
import * as XLSX from 'xlsx';
export default {
  components: {
    Add,
    ImportStudent
  },
  inject: ['reload'],
  data() {
    return {
      /*是否加载完成*/
      loading: true,
      /*列表数据*/
      tableData: [],
      /*一页多少条*/
      pageSize: 10,
      /*一共多少条数据*/
      totalDataNumber: 0,
      /*当前是第几页*/
      curPage: 1,
      /*横向表单数据模型*/
      formInline: {
        user: '',
        region: ''
      },
      /*是否打开添加弹窗*/
      open_add: false,
      /*是否打开编辑弹窗*/
      open_edit: false,
      /*当前编辑的对象*/
      curModel: {},
      /*角色列表*/
      roleList: [],
      searchForm: {
        career_id: 0,
        level_id: 0,
        direction_id: 0,
        appraisal_id: 0,
        userName: '',
        mobile: ''
      },
      positionList: [], //全部职业
      levelList: [],
      directionList: [],
      appraisalList: [],
      title: '',
      visible: false,
      successInfo: {},
      failureReasons: []
    };
  },
  created() {
    // 获取职位列表
    this.getPositionAll()
    this.getLevelAll()
    this.getDirectionAll()
    this.getAppraisalAll()
    /*获取列表*/
    this.getTableList();
  },
  methods: {
    downLoadExcel() {
      // const data = [
      //   { name: 'Alice', email: 'alice@example.com' },
      //   { name: 'Bob', email: 'bob@example.com' }
      // ];
      // 获取失败数据
      let data = []
      this.failureReasons.forEach(item => {
        if (item.result === '失败') {
          data.push({
            '手机号': item.mobile,
            '姓名': item.userName,
            '职业': item.career_title,
            '级别': item.level_title,
            '方向': item.direction_title,
            '鉴定站': item.appraisal_title,
            '备注': item.notes,
            '失败原因': item.msg,
          })
        }
      })
      this.exportToExcel(data, '学员导入失败表格')
    },
    exportToExcel(data, fileName) {
      // 将数据转换为工作表
      const worksheet = XLSX.utils.json_to_sheet(data);

      // 创建工作簿并添加工作表
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");

      // 生成Excel文件
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });

      // 将Excel文件保存到客户端
      const dataBlob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
      saveAs(dataBlob, fileName + '.xlsx');
    },
    downloadStudentTemplate() {
      window.open('https://edu.theshy.site/admin/%E5%AD%A6%E5%91%98%E6%89%B9%E9%87%8F%E4%B8%8A%E4%BC%A0%E6%A8%A1%E7%89%88.xlsx')
    },
    getPositionAll() {
      PositionApi.getNestedData({}, true)
        .then(res => {
          this.positionList = res.data;
        })
        .catch(error => { });
    },
    getLevelAll() {
      PositionApi.getCareerLevel({}, true)
        .then(data => {
          this.levelList = data.data;
        })
        .catch(error => { });
    },
    getDirectionAll() {
      PositionApi.getCareerDirection({}, true)
        .then(data => {
          this.directionList = data.data;
        })
        .catch(error => { });
    },
    getAppraisalAll() {
      PositionApi.getCareerAppraisal({}, true)
        .then(data => {
          this.appraisalList = data.data;
        })
        .catch(error => { });
    },
    /*搜索查询*/
    onSubmit() {
      this.curPage = 1;
      this.getTableList();
    },
    /*选择第几页*/
    handleCurrentChange(val) {
      let self = this;
      self.curPage = val;
      self.loading = true;
      self.getTableList();
    },

    /*每页多少条*/
    handleSizeChange(val) {
      this.curPage = 1;
      this.pageSize = val;
      this.getTableList();
    },

    /*获取列表*/
    getTableList() {
      let self = this;
      let Params = {
        ...self.searchForm
      };
      Params.page = self.curPage;
      Params.is_delete = 0;
      Params.list_rows = self.pageSize;
      StudentApi.getUserList(Params, true)
        .then(data => {
          self.loading = false;
          // self.roleList = data.data.roleList;
          self.tableData = data.data.list.data;
          self.totalDataNumber = data.data.list.total;
        })
        .catch(error => { });
    },

    /*打开添加*/
    addClick(title = '') {
      this.title = title;
      this.open_add = true;
    },

    /*关闭添加*/
    closeAdd(e) {
      this.open_add = false;
      if (e && e.type == 'success') {
        this.getTableList();
      }
    },

    /*打开编辑*/
    editClick(row) {
      console.log(row, 'row')
      this.open_add = true;
      this.$nextTick(() => {
        this.$refs.studentAdd.setTitle({
          title: row.title,
          id: row.user_id,
          data: row
        })
      })
    },

    /*关闭添加*/
    closeEdit(e) {
      this.open_edit = false;
      if (e && e.type == 'success') {
        this.successInfo = e.data || {}
        this.failureReasons = e.data && e.data.failureReasons || []
        console.log(e.data, 'data')
        this.visible = true
        this.getTableList();
      }
    },
    /*关闭添加*/
    openImport() {
      this.open_edit = true;
    },
    /*删除*/
    deleteClick(row) {
      let self = this;
      ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          self.loading = true;
          AuthApi.userDelete(
            {
              shop_user_id: row.shop_user_id
            },
            true
          )
            .then(data => {
              self.loading = false;
              if (data.code == 1) {
                ElMessage({
                  message: '恭喜你，该管理员删除成功',
                  type: 'success'
                });
                //刷新页面
                self.getTableList();
              } else {
                self.loading = false;
              }
            })
            .catch(error => {
              self.loading = false;
            });
        })
        .catch(() => { });
    }
  }
};
</script>

<style>
.active-status {
  width: 5px;
  height: 5px;
  background: #52C41A;
  margin-right: 10px;
  border-radius: 50%;
}
</style>